const http = require("http");
const path = require("path");
const fs = require("fs");
const { formidable } = require("formidable");
const sqlite3 = require("sqlite3").verbose();

// 确保files目录存在
const uploadDir = path.join(__dirname, "files");
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 数据库操作模块
const db = new sqlite3.Database(path.join(__dirname, "images.db"), (err) => {
  if (err) {
    console.error("数据库连接错误:", err.message);
  } else {
    console.log("成功连接到SQLite数据库");
    // 创建图片表
    db.run(`CREATE TABLE IF NOT EXISTS images (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      filename TEXT NOT NULL,
      originalname TEXT NOT NULL,
      mimetype TEXT NOT NULL,
      size INTEGER NOT NULL,
      uploadTime DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);
  }
});

// 基础路径和端口
const port = 3000;
const basePath = `http://localhost:${port}`;

// 创建HTTP服务器
const server = http.createServer(async (req, res) => {
  // 设置CORS
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");

  // 处理预检请求
  if (req.method === "OPTIONS") {
    res.writeHead(204);
    res.end();
    return;
  }

  const urlObj = new URL(req.url, basePath);

  // 1. 提供upload.html页面
  if (urlObj.pathname === "/upload" && req.method === "GET") {
    try {
      const filePath = path.join(__dirname, "upload.html");
      const fileContent = fs.readFileSync(filePath);
      res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
      res.end(fileContent);
    } catch (err) {
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.end("服务器错误: " + err.message);
    }
    return;
  }

  // 2. 处理文件上传
  if (urlObj.pathname === "/upload" && req.method === "POST") {
    const form = formidable({
      uploadDir: uploadDir,
      keepExtensions: true,
      maxFiles: 5, // 最多5个文件
      maxFileSize: 5 * 1024 * 1024, // 最大5MB
      filter: ({ mimetype }) => {
        // 只允许图片类型
        return mimetype && mimetype.startsWith("image/");
      },
    });

    try {
      const [fields, files] = await form.parse(req);
      const imageFiles = Array.isArray(files.images) ? files.images : [files.images];
      const results = [];

      // 保存文件信息到数据库
      for (const file of imageFiles) {
        if (file && file.filepath) {
          // 获取文件名
          const filename = path.basename(file.filepath);
          
          // 插入数据库
          await new Promise((resolve, reject) => {
            db.run(
              `INSERT INTO images (filename, originalname, mimetype, size) 
               VALUES (?, ?, ?, ?)`,
              [filename, file.originalFilename, file.mimetype, file.size],
              function (err) {
                if (err) {
                  reject(err);
                } else {
                  results.push({
                    id: this.lastID,
                    filename,
                    originalname: file.originalFilename,
                    mimetype: file.mimetype,
                    size: file.size
                  });
                  resolve();
                }
              }
            );
          });
        }
      }

      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: true,
        message: `成功上传 ${results.length} 个文件`,
        data: results
      }));
    } catch (err) {
      res.writeHead(400, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: false,
        message: "上传失败: " + err.message
      }));
    }
    return;
  }

  // 3. 获取图片列表
  if (urlObj.pathname === "/list" && req.method === "GET") {
    try {
      const images = await new Promise((resolve, reject) => {
        db.all("SELECT * FROM images ORDER BY uploadTime DESC", (err, rows) => {
          if (err) reject(err);
          else resolve(rows);
        });
      });

      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(images));
    } catch (err) {
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: false,
        message: "获取图片列表失败: " + err.message
      }));
    }
    return;
  }

  // 4. 提供图片文件访问
  if (urlObj.pathname.startsWith("/files/") && req.method === "GET") {
    try {
      const filename = path.basename(urlObj.pathname);
      const filePath = path.join(uploadDir, filename);
      
      // 检查文件是否存在
      if (!fs.existsSync(filePath)) {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("文件不存在");
        return;
      }

      const fileContent = fs.readFileSync(filePath);
      res.writeHead(200, { "Content-Type": "image/*" });
      res.end(fileContent);
    } catch (err) {
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.end("服务器错误: " + err.message);
    }
    return;
  }

  // 5. 删除图片
  if (urlObj.pathname === "/delete" && req.method === "DELETE") {
    try {
      const id = urlObj.searchParams.get("id");
      const filename = urlObj.searchParams.get("filename");
      
      if (!id || !filename) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({
          success: false,
          message: "缺少参数"
        }));
        return;
      }

      // 先删除文件
      const filePath = path.join(uploadDir, filename);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }

      // 再删除数据库记录
      await new Promise((resolve, reject) => {
        db.run("DELETE FROM images WHERE id = ?", [id], (err) => {
          if (err) reject(err);
          else resolve();
        });
      });

      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: true,
        message: "删除成功"
      }));
    } catch (err) {
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: false,
        message: "删除失败: " + err.message
      }));
    }
    return;
  }

  // 6. 处理404
  res.writeHead(404, { "Content-Type": "text/plain" });
  res.end("页面未找到");
});

// 启动服务器
server.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
  console.log(`访问 http://localhost:${port}/upload 开始使用图片管理系统`);
});

// 关闭数据库连接
process.on("SIGINT", () => {
  db.close((err) => {
    if (err) {
      console.error(err.message);
    }
    console.log("关闭数据库连接");
    process.exit(0);
  });
});
